package org.example.web;

import jakarta.annotation.Resource;
import org.example.config.LoginReactiveAuthenticationManager;
import org.example.service.TokenService;
import org.example.dto.ResultDto;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class LoginController {
    @Resource
    LoginReactiveAuthenticationManager loginReactiveAuthenticationManager;
    @Resource
    TokenService tokenService;
    @PostMapping("/auth/login")
    public Mono<ResponseEntity<ResultDto<String>>> login(String account,String password){
        //1，创建认证令牌（未认证状态）
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(account,password);
        // 2. 调用响应式认证管理器（异步处理）
        return loginReactiveAuthenticationManager.authenticate(authentication)  //调用 UserDetailsService 加载用户信息
                .map(auth ->{
                    // 3. 认证通过，提取权限并生成JWT
                    List<String> authorities = auth.getAuthorities().stream()
                            .map(ga -> ga.getAuthority())
                            .collect(Collectors.toList());
                    String token = tokenService.generateToken(auth.getName(),authorities);
                    // 返回成功响应（200 OK + 令牌）
                    return ResponseEntity.ok().body(ResultDto.<String>builder().code("ok").data(token).build());
                })
                .onErrorResume(e -> {
                    e.printStackTrace();
                    // 4. 认证失败（捕获异常，返回401 Unauthorized）
                    return Mono.just(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build());
                });
    }
}
